package logic

import (
	"context"
	"fmt"
	"meituan-waimai/models/cache"
	"meituan-waimai/models/mysql"
	"meituan-waimai/pkg"

	"meituan-waimai/meituanrpc/internal/svc"
	"meituan-waimai/meituanrpc/meituanrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateUserInfoLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateUserInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateUserInfoLogic {
	return &UpdateUserInfoLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateUserInfoLogic) UpdateUserInfo(in *meituanrpc.UpdateUserInfoRequest) (*meituanrpc.UpdateUserInfoResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Where("id = ?", in.UserId).First(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("用户不存在，请重新登录")
	}
	if in.Account != "" {
		user.Account = in.Account
	}
	if in.Password != "" {
		user.Password = pkg.Md5(in.Password)
	}
	if in.Mobile != "" {
		user.Mobile = in.Mobile
	}
	if in.HeadImage != "" {
		user.HeadImage = in.HeadImage
	}
	if in.NikeName != "" {
		user.NickName = in.NikeName
	}
	if in.PayPassword != "" {
		// 修改支付密码需要二次校验
		// 这里使用user.Mobile是因为短信发送给原手机号
		code := cache.RDB.Get(l.ctx, "SmsCode:"+user.Mobile).Val()
		if code != in.SmsCode {
			return nil, fmt.Errorf("短信验证码错误，请重新输入")
		}
		user.PayPassword = in.PayPassword
	}
	mysql.DB.Updates(&user)
	return &meituanrpc.UpdateUserInfoResponse{}, nil
}
